<!--
 * @Author: your name
 * @Date: 2021-12-05 15:41:05
 * @LastEditTime: 2021-12-06 09:13:44
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \li-yuwei\admin\src\views\knowledgeDetail\index.vue
-->
<template>
  <div class="knowledge-box">
    <a-drawer
      :title="isEdit ? '更新知识库' : '新建知识库'"
      width="620"
      :visible="visible"
      @close="onClose"
    >
      <a-form
        id="components-form-demo-validate-other"
        :form="form"
        :label-col="{ span: 2 }"
        :wrapper-col="{ span: 22 }"
      >
        <a-form-item label="名称" :colon="false">
          <a-input v-model="form.title" />
        </a-form-item>
        <a-form-item label="描述" :colon="false">
          <a-textarea :rows="4" style="resize: none" v-model="form.desc" />
        </a-form-item>
        <a-form-item label="评论" :colon="false">
          <a-switch v-model="form.is_allow_comment" />
        </a-form-item>
        <!-- ***************************** -->
        <a-form-item label="封面" :colon="false">
          <el-upload
            drag
            action
            :http-request="handleUpload"
            :before-upload="beforeUpload"
          >
            <template v-if="form.cover">
              <img :src="form.cover" alt="" height="120px" />
            </template>
            <template v-else>
              <i class="el-icon-upload"></i>
              <p class="ant-upload-text">点击选择文件或将文件拖拽到此处</p>
            </template>
          </el-upload>
        </a-form-item>
        <!-- ***************************** -->

        <a-form-item label=" " :colon="false">
          <a-input v-model="form.cover" disabled></a-input>
        </a-form-item>
        <a-form-item label=" " :colon="false">
          <a-button @click="showChildrenDrawer">选择文件</a-button>
        </a-form-item>
      </a-form>
      <a-drawer
        title="文件选择"
        width="800"
        :visible="childrenDrawer"
        @close="onChildrenDrawerClose"
      >
        <div class="box-card">
          <div class="input-box">
            <div class="title-input-box">
              <p>文件名称:</p>
              <a-input placeholder="请输入文件名称" v-model="title"> </a-input>
            </div>
            <div class="title-input-box">
              <p>文件类型:</p>
              <a-input placeholder="请输入文件类型" v-model="type"> </a-input>
            </div>
          </div>
          <div class="search-btn-box">
            <el-button type="primary" @click="searchFile">搜索</el-button>
            <el-button @click="result">重置</el-button>
          </div>
          <div class="upload-box">
            <el-upload
              action
              :http-request="handleUpload"
              :before-upload="beforeUpload"
            >
              <el-button>上传文件</el-button>
            </el-upload>
          </div>
        </div>
        <div class="card-main">
          <div
            style="width: 25%; max-width: 25%"
            v-for="item in ossList"
            :key="item.id"
            @click="valutionInfo(item)"
          >
            <a-card hoverable style="width: 95%">
              <img
                slot="cover"
                alt="example"
                :src="item.url"
                style="width: 100%; height: 150px"
              />
              <a-card-meta :title="item.name">
                <template slot="description"
                  >上传于{{ item.lastModified }}</template
                >
              </a-card-meta>
            </a-card>
          </div>
        </div>
        <a-card>
          <div class="pageination-box">
            <el-pagination
              @size-change="handleSizeChangeOss"
              @current-change="handleCurrentChangeOss"
              :current-page="pageIndex"
              :page-sizes="[8, 12, 24, 36]"
              layout="total, prev, pager, next, sizes"
              :total="ossTotal"
            >
            </el-pagination>
          </div>
        </a-card>
      </a-drawer>
      <div
        :style="{
          position: 'absolute',
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e8e8e8',
          padding: '10px 16px',
          textAlign: 'right',
          left: 0,
          background: '#fff',
          borderRadius: '0 0 4px 4px',
        }"
      >
        <a-button style="margin-right: 8px" @click="onClose"> 取消 </a-button>
        <a-button
          type="primary"
          @click="onSubmit()"
          :disabled="!isEdit && !form.title"
        >
          {{ isEdit ? "更新" : "创建" }}
        </a-button>
      </div>
    </a-drawer>
    <div class="left-box">
      <div class="left-title">
        <i class="iconfont icon-chahao"></i>
        <div class="avatar-box">
          <img :src="info.cover" alt="" />
          <span>{{ info.title }}</span>
        </div>
        <i
          class="iconfont icon-shezhi"
          style="font-size: 14px"
          @click="editDrawer(info)"
        ></i>
      </div>
      <a-button class="save-btn" @click="saveList()">保存</a-button>
      <div class="create_children_box">
        <div>{{ num }}篇文章</div>
        <el-popover
          placement="right"
          width="400"
          trigger="click"
          v-model="isShow"
        >
          <div class="new_popover">
            <el-input v-model="value"></el-input>
            <a-button type="primary" @click="createArticle">新建</a-button>
          </div>
          <a-button slot="reference">+ 新建</a-button>
        </el-popover>
      </div>
      <div
        class="article-item"
        v-for="(item, index) in addList"
        :key="index"
        @click="itemContent(item)"
      >
        <div>{{ item.title }}</div>
        <a-icon type="delete" @click.stop="delArticle(item.id)" />
      </div>
    </div>
    <div class="right-box">
      <div v-if="!isAdd" class="hint">请新建章节（或者选择章节进行编辑）</div>
      <template v-else>
        <v-md-editor
          v-model="content"
          style="width: 100%; height: 100%"
          @input="onInput"
        ></v-md-editor>
      </template>
    </div>
  </div>
</template>

<script>
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import api from "../../api";
import noImg from "../../assets/暂无.gif";
import { put, signatureUrl, getFileNameUUID, list, del } from "@/utils/oss.js";

export default {
  data() {
    return {
      id: this.$route.params.id, //详情id
      info: {},
      isAdd: false,
      fileList: [],
      type: "",
      ossList: [],
      title: "",
      // ******
      noImg,
      pageSize: 8,
      pageIndex: 1,
      currSize: 8,
      currIndex: 1,
      state: null,
      total: 0,
      ossTotal: 0,
      isEdit: false,
      visible: false, //一级抽屉开关
      childrenDrawer: false, //二级抽屉开关
      form: { title: "", desc: "", is_allow_comment: false, cover: "" },
      childrenData: [], //二级内容
      num: 0,
      value: "", //新建value
      addList: [],
      isShow: false,
      content: "", //Markdown数据
      itemId: null,
    };
  },
  methods: {
    //初始化调用
    init() {
      this.getDetailInfo();
      this.getOssFile();
    },
    //一级详情数据
    async getDetailInfo() {
      const res = await api.getKnowledgeDetail(this.id);
      this.info = await res.data;
      this.getKnowledgeChildren();
    },
    //获取二级数据
    async getKnowledgeChildren() {
      console.log(this.info.id);
      const res = await api.getKnowledgeChildren(this.info.id);
      this.addList = res.data.data;
      this.num = res.data.total;
    },
    //  自定义上传方法
    beforeUpload(file) {
      return true;
    },
    async handleUpload(option) {
      NProgress.start();
      // // 获取文件的后缀名
      var obj = option.file.name;
      var index = obj.lastIndexOf(".");
      obj = obj.substring(index, obj.length);
      // 生成的文件名，保留文件后缀名，进行拼接
      let objName = getFileNameUUID() + option.file.name;
      // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
      await put(`flieName/${objName}`, option.file).then((res) => {
        this.form.cover = res.url;
        // 上传成功之后，转换真实的地址
        signatureUrl(`flieName/${objName}`).then((res) => {
          console.log(res);
        });
      });
      NProgress.done();
    },
    //数量切换
    handleSizeChangeOss(val) {
      //设置pageSize
      this.currSize = val;
      //重新获取数据
      this.getOssFile();
    },
    //页数切换
    handleCurrentChangeOss(val) {
      //设置pageSize
      this.currIndex = val;
      //重新获取数据
      this.getOssFile();
    },
    // //重置
    result() {
      this.type = "";
      this.title = "";
      this.currSize = 8;
      this.currIndex = 1;
      this.getOssFile();
    },
    //清空各个框 并重新获取数据
    resetVal() {
      this.pageIndex = 1;
      this.state = null;
      this.searchVal = "";
      this.getKnowledgeList();
    },
    /********/
    //显示抽屉(一级)
    showDrawer() {
      this.visible = true;
    },
    //关闭抽屉(一级)
    onClose() {
      this.visible = false;
    },
    //显示抽屉(二级)
    showChildrenDrawer() {
      this.childrenDrawer = true;
    },
    //关闭抽屉(二级)
    onChildrenDrawerClose() {
      this.childrenDrawer = false;
    },
    editDrawer(data) {
      this.isEdit = true;
      this.form = {
        ...data,
        url: data.cover,
        is_allow_comment: Boolean(data.is_allow_comment * 1), //数字(字符串类型数字)转布尔
      };
      this.showDrawer();
    },
    //提交按钮
    async onSubmit() {
      //判断是否为编辑
      if (this.isEdit) {
        //调用接口
        const res = await api.editKnowledgeList({
          id: this.form.id,
          title: this.form.title,
          state: this.form.data,
          desc: this.form.desc,
          is_allow_comment: Number(this.form.is_allow_comment),
          cover: this.form.cover,
        });
        //重新渲染
        if (res.success) {
          this.getDetailInfo();
          this.$message({
            type: "success",
            message: "更新成功",
          });
        } else {
          this.$message({
            type: "warning",
            message: "意外的错误",
          });
        }
      } else {
        const res = await api.addKnowledgeList({
          title: this.form.title,
          state: 0,
          desc: this.form.desc,
          is_allow_comment: Number(this.form.is_allow_comment),
          cover: this.form.cover,
        });
        if (res.success) {
          this.$message({
            type: "success",
            message: "创建成功",
          });
          this.getKnowledgeList();
        } else {
          this.$message({
            type: "warning",
            message: "意外的错误",
          });
        }
      }
      this.onClose();
    },
    //获取oss数据
    async getOssFile() {
      //显示加载进度条--->提示用户加载进度
      NProgress.start();
      const res = await list();
      this.ossList = res.objects;
      //结束用户加载进度
      this.ossList.sort((a, b) => {
        return new Date(b.lastModified) - new Date(a.lastModified);
      });
      this.ossList = this.ossList.map((item) => {
        return {
          ...item,
          name: item.name.split("flieName/")[1],
          path: item.name,
          type: "image/" + item.name.split(".")[1],
        };
      });
      let newList = this.ossList;
      this.ossTotal = newList.length;
      if (this.title) {
        newList = newList.filter((item) => item.name.includes(this.title));
      }
      if (this.type) {
        newList = newList.filter((item) => item.type.includes(this.type));
      }
      this.ossList = newList.slice(
        (this.currIndex - 1) * this.currSize,
        this.currSize * this.currIndex
      );
      this.ossTotal = newList.length;
      NProgress.done();
    },
    //搜索事件
    searchFile() {
      this.currIndex = 1;
      this.getOssFile();
    },
    //赋值cover封面信息
    valutionInfo(data) {
      this.form = { ...this.form, cover: data.url };
      this.onChildrenDrawerClose();
    },
    //创建新文章
    async createArticle() {
      this.isShow = false;
      await this.addList.unshift({
        title: this.value,
        id: Math.random().toString(16).slice(2),
        content: "",
        knowledge_id: this.info.id,
        author: "嗯呢",
      });
      this.value = "";
      this.num = this.addList.length;
      this.isAdd = true;
      this.itemId = this.addList[0].id;
    },
    //删除
    delArticle(id) {
      const index = this.addList.findIndex((item) => item.id === id);
      this.addList.splice(index, 1);
      this.num = this.addList.length;
    },
    //输入事件
    onInput() {
      const index = this.addList.findIndex((item) => item.id === this.itemId);
      this.addList[index].content = this.content;
    },
    //循环文章目录
    itemContent(item) {
      this.content = item.content;
      this.itemId = item.id;
      this.isAdd = true;
    },
    async saveList() {
      console.log(this.addList);
      const res = await api.addKnowledgeChildren({ addList: this.addList });
      console.log(res);
    },
  },
  created() {
    this.init();
  },
};
</script>

<style lang="scss" scoped>
.knowledge-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: flex-start;
  .left-box {
    width: 245px;
    height: 100%;
    background-color: #e7eaee;
    padding: 0 10px;
  }
  .right-box {
    flex: 1;
    height: 100%;
  }
}
.left-title {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  .iconfont {
    font-size: 12px;
    color: #000;
  }
  .avatar-box {
    display: flex;
    align-items: center;
  }
  img {
    width: 40px;
    height: 40px;
    margin-right: 10px;
  }
}
.save-btn {
  width: 100%;
  margin: 10px 0;
}
.hint {
  text-align: center;
  margin-top: 350px;
  color: #000;
  font-size: 16px;
}
.create_children_box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2px;
  border-bottom: 1px solid rgb(218, 214, 214);
  padding-bottom: 10px;
  .create_btn {
    padding: 2px 16px;
  }
}
.new_popover {
  width: 370px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.el-input {
  margin-right: 20px;
}
.article-item {
  display: flex;
  justify-content: space-between;
  background-color: #f8f8f8;
  align-items: center;
  margin: 10px 0;
  padding: 15px 10px;
  border-radius: 2px;
}
</style>
<style scoped lang="scss">
.pagination-box {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.create-box {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
  .create-btn {
    padding: 10px 20px;
    border-radius: 2px;
  }
}
.main-card {
  margin-top: 20px;
}
.table-box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .ant-card {
    padding: 8px;
  }
}
.pre-img {
  width: 100%;
  height: 150px;
  display: inline-block;
  padding: 20px 0;
  background-color: #f5f5f5;
  border: 1px solid #ccc;
}
.box-card {
  width: 100%;
  .input-box {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
  }
}
.input-box .title-input-box {
  display: flex;
  align-items: center;
  p {
    width: 95px;
  }
}
.search-btn-box {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.card-main {
  width: 100%;
  background-color: #fff;
  display: flex;
  flex-wrap: wrap;
  padding: 20px;
  .ant-card {
    padding: 20px;
    border: none;
    margin: 5px;
    margin-top: 20px;
    margin-bottom: 20px;
  }
}
.pageination-box {
  display: flex;
  justify-content: flex-end;
}
.info-box {
  font-size: 12px;
  margin: 15px 0;
  color: #000;
}
.copy-link {
  display: flex;
  margin-bottom: -30px;
  span {
    width: 55px;
    flex-shrink: 0;
    flex-wrap: wrap;
  }
  p {
    width: 510px;
    flex-shrink: 0;
    border: 1px solid #ccc;
    padding: 5px;
  }
}
.upload-box {
  display: flex;
  justify-content: flex-end;
}
</style>
